package com.heima.wemedia.service.impl;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.WmNewsMessageConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.dtos.WmUserDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVo;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.boot.system.ApplicationHome;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    String webSite;

    @Resource
    private WmMaterialMapper wmMaterialMapper;

    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Resource
    private KafkaTemplate kafkaTemplate;

    @Resource
    private WmNewsMapper wmNewsMapper;

    @Resource
    private WmUserMapper wmUserMapper;
    /**
     * 自媒体文章人工审核
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {

        if(dto==null || dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(dto.getId());

        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        wmNews.setStatus(status);

        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult();
        responseResult.setHost(webSite);
        return responseResult;
    }

    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        dto.checkParam();
        int currentPage = dto.getPage();
        dto.setPage((dto.getPage()-1)*dto.getSize());
        if(StringUtils.isNotBlank(dto.getTitle())){
            dto.setTitle("%"+dto.getTitle()+"%");
        }
        //2.分页查询
        List<WmNewsVo> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);
        // 3. 封装返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(currentPage,dto.getSize(),(int)count);
        pageResponseResult.setData(wmNewsVoList);
//        pageResponseResult.setHost();
        return pageResponseResult;
    }


    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        dto.checkParam();

        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();

        if(StringUtils.isNotBlank(dto.getKeyword())){
            wrapper.like(WmNews::getTitle,dto.getKeyword());
        }

        if(dto.getChannelId()!=null){
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }

        if(dto.getStatus()!=null){
            wrapper.eq(WmNews::getStatus,dto.getStatus());
        }

        if(dto.getBeginPubDate()!=null && dto.getEndPubDate()!=null){
            wrapper.between(WmNews::getSubmitedTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }

        WmUser wmUser = WmThreadLocalUtils.getUser();

        if(wmUser == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        wrapper.eq(WmNews::getUserId,wmUser.getId());

        wrapper.orderByDesc(WmNews::getCreatedTime);

        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());

        IPage<WmNews> pageResult = page(page, wrapper);

        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int)pageResult.getTotal());

        result.setData(pageResult.getRecords());

        result.setHost(webSite);

        return result;
    }



    @Override
    public List<Integer> findRelease() {
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery()
                .in(WmNews::getStatus, 4, 8)
                .le(WmNews::getPublishTime, new Date())
                .select(WmNews::getId));

        List<Integer> idList = list.stream().map(WmNews::getId).collect(Collectors.toList());
        return idList;
    }

    @Override
    public ResponseResult submitNews(WmNewsDto wmNewsDto, Short isSubmit) {
        if(wmNewsDto==null || StringUtils.isBlank(wmNewsDto.getContent())){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNews wmNews = new WmNews();

        BeanUtils.copyProperties(wmNewsDto,wmNews);

        if(wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }

        String images = imageListToStr(wmNewsDto.getImages(),webSite);

        //保存或修改
        saveOrUpdateWmNews(wmNews);

        //3.1 抽取文章中关联的图片路径
        String content = wmNews.getContent();
        List<String> materials = parseContentImages(content);

        //3.2 关联文章内容中的图片和素材关系

        if(isSubmit==WmNews.Status.SUBMIT.getCode() && materials.size()>0){
            saveRelativeInfoForContent(materials, wmNews.getId());
        }

        //3.3 关联文章封面中的图片和素材关系  封面可能是选择自动或者是无图
        if (isSubmit == WmNews.Status.SUBMIT.getCode()) {
            saveRelativeInfoForCover(wmNewsDto,materials, wmNews);
        }

        HashMap hashMap = new HashMap();
        hashMap.put("wmNewsId", wmNews.getId());
        kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC,JSON.toJSONString(hashMap));
        return ResponseResult.okResult();
    }


    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if(dto==null&&dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNews wmNews = getById(dto.getId());
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }

        if(wmNews.getEnable()!=null && wmNews.getEnable()>-1 && wmNews.getEnable()<2){
            update(Wrappers
                    .<WmNews>lambdaUpdate()
                    .eq(WmNews::getId,dto.getId())
                    .set(WmNews::getEnable,dto.getEnable()));
        }

        if(wmNews.getArticleId()!=null){
            HashMap<String,Object> map = new HashMap<>();
            map.put("enable",dto.getEnable());
            map.put("articleId",wmNews.getArticleId());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult delNews(Integer id) {
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        WmNews wmNews = getById(id);
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())&&wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UPENABLE)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }

        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getNewsId,wmNews.getId()));

        removeById(wmNews.getId());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        if(id==null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNews byId = getById(id);
        if(byId==null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        ResponseResult result = ResponseResult.okResult(byId);
        result.setHost(webSite);
        return result;
    }


    private void saveRelativeInfoForCover(WmNewsDto wmNewsDto, List<String> materials, WmNews wmNews) {
        List<String> images = wmNewsDto.getImages();
        if(WemediaConstants.WM_NEWS_TYPE_AUTO.equals(wmNewsDto.getType())){
            int materialSize = images.size();
            if(materialSize>0&&materialSize<=2){
                images = materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }else if(materialSize > 2){
                images = materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }else{
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if(images!=null && images.size()>0){
                wmNews.setImages(imageListToStr(images,webSite));
            }
            updateById(wmNews);
        }

        if(images!=null && images.size()>0){
            images = images.stream()
                    .map(url -> url.replace(webSite, ""))
                    .collect(Collectors.toList());
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);
        }

    }

    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials,newsId,WemediaConstants.WM_CONTENT_REFERENCE);
    }

    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .in(WmMaterial::getUrl, materials)
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));

        //2 校验素材列表
        if (wmMaterials == null || wmMaterials.size() == 0) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        List<Integer> materialIds = new ArrayList<>();
        Map<String, Integer> materialMap = wmMaterials.stream()
                .collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));

        for (String material : materials) {
            Integer id = materialMap.get(material);
            if (id == null) {
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            materialIds.add(id);
        }

        wmNewsMaterialMapper.saveRelations(materialIds,newsId,type);
    }


    private List<String> parseContentImages(String content) {
        List<Map> contents = JSON.parseArray(content, Map.class);
        return contents.stream()
                .filter((map)->map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE))
                .map(map->map.get("value"))
                .map((imageUrl)-> webSite.replace(webSite,""))
                .collect(Collectors.toList());
    }


    private String imageListToStr(List<String> images, String webSite) {
        return images.stream().map((url)->url.replace(webSite,"")).collect(Collectors.joining(","));
    }


    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UPENABLE);
        if(wmNews.getId()==null){
            save(wmNews);
        }else{
            wmNewsMaterialMapper.delete(Wrappers
                    .<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
        }

    }




}